package dayu

import (
	"errors"
	"fmt"
	"io"
	"regexp"
	"strconv"
	"time"

	"publish/pub-lib/utils"
	"github.com/astaxie/beego"
)

type DayuApi struct {
	ck     string
	utoken string
	author string
}

func NewDayuApi(ck string) *DayuApi {

	api := &DayuApi{
		ck: ck,
	}
	api.utoken = api.getUtoken()
	return api
}

func (q *DayuApi) CheckCookie() error {
	req := utils.Get(`https://mp.dayu.com/dashboard/index`)

	req.Header("Cookie", q.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
	bys, err := req.Bytes()
	if err != nil {
		return err
	}

	reg := regexp.MustCompile(`"utoken":"([^"]+)"`)
	results := reg.FindAllStringSubmatch(string(bys), -1)
	if len(results) > 0 {
		result := results[0]
		if len(result) == 2 {
			return nil
		}
	}
	return errors.New("cookie 无效")
}

func (q *DayuApi) getUtoken() string {
	req := utils.Get(`https://mp.dayu.com/dashboard/index`)

	req.Header("Cookie", q.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
	bys, err := req.Bytes()
	if err != nil {
		return ""
	}

	reg := regexp.MustCompile(`"utoken":"([^"]+)"`)
	results := reg.FindAllStringSubmatch(string(bys), -1)
	if len(results) > 0 {
		result := results[0]
		if len(result) == 2 {
			return result[1]
		}
	}
	return ""
}

func (q *DayuApi) uploadImageByUrl(url string) (*UrlResponse, error) {
	req := utils.Get(`https://mp.dayu.com/upload-image`)

	req.Header("Cookie", q.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")

	req.Param("src", url)
	req.SetTimeout(10*time.Second, 10*time.Second)

	urlImage := UrlResponse{}
	if err := req.ToJSON(&urlImage); err != nil {
		return nil, err
	}

	return &urlImage, nil
}

func (q *DayuApi) uploadImageByFile(reader io.ReadCloser, filename string, size int64) (*ImageResponse, error) {
	req := utils.Post(`https://mp.dayu.com/imageupload`)

	req.Header("Cookie", q.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")

	req.Param("id", "WU_FILE_0")
	req.Param("name", filename)
	req.Param("type", "image/png")
	req.Param("lastModifiedDate", time.Now().String())
	req.Param("size", strconv.FormatInt(size, 10))
	req.PostFileByStream("upfile", filename, reader)

	fileImage := ImageResponse{}
	if err := req.ToJSON(&fileImage); err != nil {
		return nil, err
	}

	return &fileImage, nil
}

func (q *DayuApi) cuttingImageByUrl(url string) (*UrlResponse, error) {
	req := utils.Post(`https://mp.dayu.com/imagecut`)

	req.Header("Cookie", q.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
	req.Header("utoken", q.utoken)

	req.Param("src", url)
	req.Param("x", "0")
	req.Param("y", "35")
	req.Param("ow", "640")
	req.Param("oh", "361")
	req.Param("w", "640")
	req.Param("h", "361")
	req.Param("utoken", q.utoken)
	req.SetTimeout(10*time.Second, 10*time.Second)

	urlImage := UrlResponse{}
	if err := req.ToJSON(&urlImage); err != nil {
		return nil, err
	}
	return &urlImage, nil
}

//保存草稿
func (q *DayuApi) save(article *DArticle) (string, error) {

	req := utils.Post(`https://mp.dayu.com/dashboard/save-draft`)

	req.Header("Cookie", q.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
	req.Header("utoken", q.utoken)

	req.Param("isPaste", "1")
	req.Param("draft_id", "")
	req.Param("article_id", "")
	req.Param("title", article.Title)
	req.Param("content", article.Content)
	req.Param("author", article.Author)
	req.Param("coverImg", article.CoverImages)
	req.Param("article_type", "1")
	req.Param("aoyun", "false")
	req.Param("weixin_promote", "false")
	req.Param("is_original", "0")
	req.Param("article_activity_title", "")
	req.Param("article_activity_id", "")
	req.Param("open_award", "0")
	req.Param("open_reproduce", "0")
	req.Param("is_show_ad", "false")
	req.Param("defaultAuthor", "false")
	req.Param("curDaySubmit", "false")
	req.Param("simpleMode", "true")
	req.Param("is_timed_release", "false")
	req.Param("time_for_release", "1514353730955")
	req.Param("keyword", "")
	req.Param("useTime", "16062")
	req.Param("utoken", q.utoken)
	req.SetTimeout(30*time.Second, 30*time.Second)

	pub := PubResponse{}
	if err := req.ToJSON(&pub); err != nil {
		beego.Error("大鱼获取 cookie 授权失败：", article.Title, err)
		return "", errors.New("cookie 授权失败")
	}
	if len(pub.Data.Id) <= 0 {
		return "", errors.New("no find the pub result id")
	}

	return pub.Data.Id, nil
}

func (q *DayuApi) publish(aid string) error {
	req := utils.Post(`https://mp.dayu.com/dashboard/submit-article`)

	req.Header("Cookie", q.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
	req.Header("utoken", q.utoken)

	req.Param("dataList[0][_id]", aid)
	req.Param("dataList[0][isDraft]", "1")
	req.Param("dataList[0][reproduce]", "")
	req.Param("curDaySubmit", "false")
	req.Param("utoken", q.utoken)

	pub := PubResponse{}

	if err := req.ToJSON(&pub); err != nil {
		return err
	}

	if len(pub.Data.Id) <= 0 {
		return errors.New(pub.Error)
	}

	return nil
}

func (q *DayuApi) saveGallery(gallery *Gallery) (string, error) {
	req := utils.Post(`https://mp.dayu.com/dashboard/save-draft`)

	req.Header("Cookie", q.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
	req.Header("utoken", q.utoken)

	req.Param("title", gallery.Title)
	req.Param("description_type", "1")
	req.Param("draft_id", "")
	req.Param("article_category", "2")
	req.Param("coverImg", gallery.CoverImg)
	req.Param("article_type", "1")
	req.Param("category", "")
	req.Param("utoken", q.utoken)

	for _, kv := range gallery.Images {
		fmt.Println(kv.K + ":" + kv.V)
		req.Param(kv.K, kv.V)
	}

	pub := PubResponse{}
	if err := req.ToJSON(&pub); err != nil {
		return "", err
	}
	if len(pub.Data.Id) <= 0 {
		return "", errors.New("no find the pub result id")
	}
	fmt.Println(pub)

	return pub.Data.Id, nil
}

func (q *DayuApi) publishGallery(aid string) error {
	req := utils.Post(`https://mp.dayu.com/dashboard/submit-fastfish`)

	req.Header("Cookie", q.ck)
	req.Header("Accept-Encoding", "gzip, deflate")
	req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
	req.Header("utoken", q.utoken)

	req.Param("dataList[0][_id]", aid)
	req.Param("dataList[0][isDraft]", "1")
	req.Param("utoken", q.utoken)

	pub := PubResponse{}
	if err := req.ToJSON(&pub); err != nil {
		return err
	}
	fmt.Println(pub)
	return nil
}




